<template>
  <BasicModal @register="registerFormModal" title="新增告警配置" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
  <BasicModal v-bind="$attrs" @register="registerModal" title="告警配置" width="1000px" @ok="handleSubmitAlarm">
    <BasicTable @register="registerTable" ref="selectTable" showTableSetting>
      <template #toolbar>
        <a-button type="primary" @click="addNewConfig">添加配置</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]" />
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts" setup>
import { BasicModal, useModal, useModalInner } from '@/components/Modal';
import { BasicTable, FormSchema, useTable, TableAction } from '@/components/Table';
import { alarmConfigColumns } from './device.data';
import { reactive, ref } from 'vue';
import { addDeviceAlarm, getDeviceAlarmList, getDevicePropertyList, deleteDeviceAlarm } from '@/api/collection/device';
import { BasicForm, useForm } from '@/components/Form/index';
import { getAlarmTypeList } from '@/api/alarm/alarm';

const dataSourceRef = ref();
const currentDevciceId = ref();
const searchInfo = reactive<Recordable>({ deviceId: 0 });

const alarmConfigFormSchema: FormSchema[] = [
  {
    label: '参数属性名称',
    field: 'devicePropertyName',
    component: 'ApiSelect',
    componentProps: ({ formModel, formActionType }) => {
      return {
        api: getDevicePropertyList,
        labelField: 'name',
        valueField: 'id',
        params: currentDevciceId.value
      }
    },
    required: true,
  },
  {
    field: 'maxValue',
    label: '上限值',
    component: 'InputNumber',
    required: true,
  },
  {
    label: '下限值',
    field: 'minValue',
    component: 'InputNumber',
    dynamicRules: ({ values }) => {
      return [
        {
          required: true,
          validator: (_, value) => {
            if (value > values.maxValue) {
              return Promise.reject('下限值不能大于上限值')
            }
            return Promise.resolve()
          },
        },
      ]
    },
    required: true,
  },
  {
    label: '告警类型',
    field: 'alarmTypeName',
    component: 'ApiSelect',
    componentProps: ({ formModel, formActionType }) => {
      return {
        api: getAlarmTypeList,
        labelField: 'name',
        valueField: 'id',
        params: currentDevciceId.value
      }
    },
    required: true,
  },
];

const [registerTable, { reload }] = useTable({
  canResize: true,
  // dataSource: dataSourceRef,
  api: getDeviceAlarmList,
  columns: alarmConfigColumns,
  rowKey: 'id',
  showTableSetting: false,
  searchInfo,
  actionColumn: {
    width: 120,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  },
});

const [registerFormModal, { openModal: openFormModal }] = useModal();

const [registerModal, { closeModal }] = useModalInner(async (data) => {
  currentDevciceId.value = { deviceId: data.record.id };
  // fetch(data);
  searchInfo.deviceId = data.record.id;
  reload();
})

const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: alarmConfigFormSchema,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 23,
  },
});

const fetch = async (data) => {
  const ret = await getDeviceAlarmList({ deviceId: data.record.id });
  dataSourceRef.value = ret;
}

const addNewConfig = () => {
  openFormModal(true, {
    isUpdate: false,
  });
}

const handleDelete = async (record) => {
  await deleteDeviceAlarm({ id: record.id })
  reload()
  // const ret = await getDeviceAlarmList(currentDevciceId.value);
  // dataSourceRef.value = ret;
}

const handleSubmit = async () => {
  try {
    const values = await validate();
    const params = {
      ...values,
      deviceId: currentDevciceId.value.deviceId,
      devicePropertyId: values.devicePropertyName,
      alarmTypeId: values.alarmTypeName,
    }
    await addDeviceAlarm(params);
    openFormModal(false);
    closeModal();
    reload();
    // const ret = await getDeviceAlarmList(currentDevciceId.value);
    // dataSourceRef.value = ret;
  } catch (e) {
    //TODO handle the exception
  }
}


const handleSubmitAlarm = () => closeModal();

</script>
